package vip.youngboy.freejump.parse.user;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import vip.youngboy.freejump.domain.FlowRequestParam;
import vip.youngboy.freejump.domain.process.ChooseResult;
import vip.youngboy.freejump.domain.process.UserOptions;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Component
public class UserSettingParser {

    private Map<String, UserSettingParse> userSettingParseMap = new HashMap<>();

    @Autowired
    public void setUserSettingParse(List<UserSettingParse> userSettingParses) {
        if (!userSettingParses.isEmpty()) {
            this.userSettingParseMap = userSettingParses.stream().collect(Collectors.toMap(handle -> handle.supportType(), handle -> handle));
        }
    }

    /**
     * 解析前端上传人员选项
     *
     * @param flowRequestParam 前端上传的人员解析信息
     * @return 解析后得人员
     */
    public Set<String> parseUserOptions(FlowRequestParam flowRequestParam) {
        JSONObject userOptions = flowRequestParam.getUserOptions();
        UserOptions userChoose = userOptions.toJavaObject(UserOptions.class);
        //删除前端groovy类型脚本，前端人员不能选择groovy类型人员解析
        userChoose.getResult().removeIf(item -> item.getType().equalsIgnoreCase("groovy"));
        return parseUserOptions(userChoose);
    }

    /**
     * 解析用户选项
     *
     * @param userOptions 用户选项
     * @return 用户选项
     */
    public Set<String> parseUserOptions(UserOptions userOptions) {
        Set<String> candidateUsers = Sets.newHashSet();
        for (ChooseResult chooseResult : userOptions.getResult()) {
            candidateUsers.addAll(parseChooseResult(chooseResult));
        }
        if (candidateUsers.isEmpty()) {
            log.info("解析用户为空");
        }
        return candidateUsers;
    }

    /**
     * 解析选择结果
     *
     * @param chooseResult 选择结果
     * @return 解析后的人员
     */
    public Set<String> parseChooseResult(ChooseResult chooseResult) {
        Set<String> candidateUsers = Sets.newHashSet();
        String type = chooseResult.getType();
        UserSettingParse userSettingParse = userSettingParseMap.get(type);
        if (userSettingParse == null) {
            log.info("{} 类型 解析器为空", type);
        } else {
            //无解析类型
            candidateUsers.addAll(userSettingParse.parse(chooseResult));
        }
        return candidateUsers;
    }


}
